package history.hot100;

import java.util.Arrays;

// 581. 最短无序连续子数组:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
// 题解：https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/solution/zui-duan-wu-xu-lian-xu-zi-shu-zu-shuang-f1dsr/
public class LeetCode_581 {
    public int findUnsortedSubarray(int[] nums) {
        if (nums.length <=1) return 0;
        int n = nums.length;
        int []numsSort = nums.clone();
        Arrays.sort(numsSort);
        int left = Integer.MAX_VALUE, right =0;
        for (int i = 0; i < n; i++) {
            if (numsSort[i] != nums[i]) {
                left = i;
                break;
            }
        }
        for (int i = n-1; i >= 0 ; i--) {
            if (numsSort[i] != nums[i]) {
                right = i;
                break;
            }
        }
        if (right - left >= 0) return right - left +1;
        return 0;
    }
}
